<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function TreeNode(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        let a = new TreeNode(1)
        let b = new TreeNode(3)
        let c = new TreeNode(2)
        let d = new TreeNode(5)
        a.left = b
        a.right = c
        b.left = d

        let aa = new TreeNode(2)
        let bb = new TreeNode(1)
        let cc = new TreeNode(3)
        let dd = new TreeNode(4)
        let ee = new TreeNode(7)
        let ff = new TreeNode(1)
        let gg = new TreeNode(7)
        aa.left = bb
        aa.right = cc
        bb.right = dd
        cc.right = ee
        ee.right = gg
        bb.left = ff

        let aaa = new TreeNode(1)
        let bbb = new TreeNode(2)
        aaa.right = bbb

        let ccc = new TreeNode(0)
        /* 
        时间O(n) n是最多递归的次数
        空间O(n) n是result节点的占用
        思路：递归：修改中序遍历，pre节点和当前节点比较，相等，count就++，count还要和一个最大值进行比较，如果相等，当前值就放入数组，如果大于max，就清空result数组，当前值再放进去
        */
        // 1. 声明变量
        let pre
        let count
        let maxCount
        let result
        let obj = {}
        var findMode = function (root) {
            debugger
            // 2. 变量初始值
            pre = null
            count = 0
            maxCount = 0
            result = []
            // 3. 调用递归
            searchBST(root)
            return result
        };
        function searchBST(node) {
            debugger
            // 4. 递归退出条件
            if (node === null) {
                return
            }
            // 5. 左边递归
            searchBST(node.left)
            // 6. 中间节点的处理
            // 如果上一个节点的值是null 就是根节点 count是1
            if (pre === null) {
                count = 1
            } else if (pre.val === node.val) {
                // 如果值相等 说明计数器要更新
                count++
            } else {
                // 如果不相等，说明计数器中断了
                count = 1
            }

            // count要和最大值进行比较 如果count值 === maxCount 比如之前已经有两个3了，现在的count也是2，现在的node.val是5，表示现在也有2个5，那么5这个数也要放进去结果数组
            // 如果现在的count是3，node.val是6，表示有3个6，超过了2个3，就要把之前的3给移出出去
            if (count === maxCount) {
                result.push(node.val)
            } else if (count > maxCount) {
                result = []
                result.push(node.val)
                // 更新现在的最大值
                maxCount = count
            }
            // 更新上一个节点的值
            pre = node
            // 9. 右边递归
            searchBST(node.right)
            return
        }
        // console.log(findMode(aa));
        console.log(findMode(ccc));
    </script>
</body>

</html>